package com.efast.standalone.open;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jws.WebService;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.efast.standalone.bean.ResultBean;
import com.efast.standalone.dao.PmFeaturValueDao;
import com.efast.standalone.dao.PmPartModelAndVinRuleDao;
import com.efast.standalone.dao.PmSerialnumberDao;
import com.efast.standalone.dao.PrBasLoadingListDao;
import com.efast.standalone.dao.PrintDao;
import com.efast.standalone.dao.TwBasLotDao;
import com.efast.standalone.enti.PmFeaturValue;
import com.efast.standalone.enti.PmPartModelAndVinRule;
import com.efast.standalone.enti.PmSerialnumber;
import com.efast.standalone.enti.PrBasLoadingList;
import com.efast.standalone.enti.Print;
import com.efast.standalone.enti.TwBasLot;
import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPrintServiceExporter;
import net.sf.jasperreports.engine.export.JRPrintServiceExporterParameter;

@WebService(name = "webservices" ,targetNamespace ="http://services" ,endpointInterface = "com.efast.standalone.open.WebServices")
@Service
public class WebServicesImpl  implements WebServices{

	@Autowired
    private PrintDao printDao;
	@Autowired
	private PmSerialnumberDao pmSerialnumberDao;
	
	@Autowired
	private TwBasLotDao lotDao;
	@Autowired
	private PmFeaturValueDao pmFeaturValueDao;
	@Autowired
	private PrBasLoadingListDao listDao;
	@Autowired
	private PmPartModelAndVinRuleDao vinRuleDao;
	public void WebServiceImpl() {
		
	}
		
//单次打印零部件
	@Override
	public String zebraPrintPartNo(String json) {
		Boolean isExist = false;
		Map<?, ?> map = (Map<?, ?>) JSON.parse(json);
		// 获取打印参数数据
		String partNo = (String) map.get("partNo");
		String printType = (String) map.get("printType");
		Boolean printStatus = (Boolean) map.get("printStatus");
		String printName = (String) map.get("printName");
		String printUser = (String) map.get("printUser");
		String templateName = (String) map.get("templateName");
		if (printStatus) {
			List<Print> list = printDao.isExistPrintLog(partNo, printType);
			if(list.size()>0) {
				return "已存在打印记录，请进行重打印！";
			}
		} 
		// 保存打印记录
		Print prBasPrintVinLabel = new Print();
		prBasPrintVinLabel.setVin(partNo);
		prBasPrintVinLabel.setPrintType(printType);
		prBasPrintVinLabel.setPrint_user(printUser);
		prBasPrintVinLabel.setPrintType(printType);
		prBasPrintVinLabel.setTemplateName(templateName);
		prBasPrintVinLabel.setPrintName(printName);
		if (printStatus) {
			prBasPrintVinLabel.setPrint_status("1");
		} else {
			prBasPrintVinLabel.setPrint_status("2");
		}

		prBasPrintVinLabel.setPrint_time(new Date());
		printDao.savePrintInfo(prBasPrintVinLabel);
		SimpleDateFormat yf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date d = new Date();
		String data = yf.format(d);
		String filePath = "C://printTemplate//" + templateName + ".zpl";
		try {
			FileReader fileReader = new FileReader(filePath);
			BufferedReader br = new BufferedReader(fileReader);
			String strs = "";
			String datas = null;
			while ((datas = br.readLine()) != null) {
				strs = strs + datas;
			}
			try {
				fileReader.close();
				br.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
			strs = strs.replace("$", partNo);
			System.out.println(strs);
			if (strs == null || "".equals(strs)) {
				System.out.println("打印" + partNo + "无法获取零部件标签打印模板");
			}
		// TODO Auto-generated method stub
		File fileName = new File("C:\\temp\\zebra\\" + partNo + "partNo" + data + ".zpl");
		File fileParent = fileName.getParentFile();

		if (!fileParent.exists()) {
			fileParent.mkdirs();
		}

		try {
			fileName.createNewFile();
			FileOutputStream outStream = new FileOutputStream(fileName);
			OutputStreamWriter out = new OutputStreamWriter(outStream, "UTF-8");
//			out.write("^XA");
//			out.write("^MMT");
//			out.write("^PW827");
//			out.write("^LL0236");
//			out.write("^LS0");
//			out.write("^BY4,3,116^FT59,162^BCN,,Y,N");
//			out.write("^FD" + partNo + "^FS");
//			out.write("^PQ1,0,1,Y");
//			out.write("^XZ");
			out.write(strs);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("-------------------------------------生成本地文件成功了！它在C:\\temp\\zebra的目录下");
		HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
		DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
		// 获取本机的打印服务
		PrintService[] printService = PrintServiceLookup.lookupPrintServices(flavor, pras);
		for (PrintService printer : printService) {
			if (printer.getName().equals(printName)) {
				DocPrintJob job = printer.createPrintJob();
				try {
					FileInputStream in = new FileInputStream(fileName);
					SimpleDoc doc = new SimpleDoc(in, flavor, null);
					try {
						System.out.println("-------------------------------------开始打印了");
						isExist = true;
						job.print(doc, null);
					} catch (PrintException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		 }
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		if (!isExist) {
			return  "无法获取本地打印机";
		}

		return null;
	}

	@SuppressWarnings("resource")
	@Override
	public String zebraPrintPartNoList(String json) {
		// TODO Auto-generated method stub
		Boolean isExist = false;
		Map<?, ?> map = (Map<?, ?>) JSON.parse(json);
		// 获取打印参数数据
		String partNo = (String) map.get("partNo");
		String printType = (String) map.get("printType");
		String printName = (String) map.get("printName");
		String printUser = (String) map.get("printUser");
		String templateName = (String) map.get("templateName");
		int beginNo =(Integer) map.get("beginNo");
		int endNo =(Integer) map.get("endNo");
		//去掉零部件后两位
		String partNo1=partNo.substring(0, partNo.length()-2);
		String partNoNew;
		String filePath = "C://printTemplate//" + templateName + ".zpl";
		
		try {
			FileReader fileReader = new FileReader(filePath);
			BufferedReader br = new BufferedReader(fileReader);
			String strs = "";
			String datas = null;
			while ((datas = br.readLine()) != null) {
				strs = strs + datas;
			}
			try {
				fileReader.close();
				br.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			for(int i=beginNo;i<=endNo;i++) {
				if(i<10) {				
					StringBuffer bfBufferProNumber=new StringBuffer(String.valueOf(i));
		    		bfBufferProNumber.reverse();
		    		int size=2-bfBufferProNumber.length();
		    		for(int j=0;j<size;j++) {
		    			bfBufferProNumber.append("0");
		    		}
		    		bfBufferProNumber.reverse();
		    		partNoNew=partNo1+bfBufferProNumber;
				}else {
					partNoNew=partNo1+String.valueOf(i);
				}
				//保存打印记录
				Print prBasPrintVinLabel= new Print();
				prBasPrintVinLabel.setVin(partNoNew);
				prBasPrintVinLabel.setPrintType(printType);
				prBasPrintVinLabel.setPrint_status("1");					
				prBasPrintVinLabel.setPrint_time(new Date());
				prBasPrintVinLabel.setPrint_user(printUser);
				prBasPrintVinLabel.setPrintType(printType);
				prBasPrintVinLabel.setTemplateName(templateName);
				prBasPrintVinLabel.setPrintName(printName);
				printDao.savePrintInfo(prBasPrintVinLabel);
				SimpleDateFormat yf = new SimpleDateFormat("yyyyMMddHHmmss");
				Date d = new Date();
				String data = yf.format(d);
				String strs1=strs;
				strs1 = strs1.replace("$", partNoNew);
				// TODO Auto-generated method stub
				File fileName = new File("C:\\temp\\zebra\\" + partNoNew + "partNo" + data + ".zpl");
				File fileParent = fileName.getParentFile();

				if (!fileParent.exists()) {
					fileParent.mkdirs();
				}

				try {
					fileName.createNewFile();
					FileOutputStream outStream = new FileOutputStream(fileName);
					OutputStreamWriter out = new OutputStreamWriter(outStream, "UTF-8");
					out.write(strs1);
					out.flush();
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("-------------------------------------生成本地文件成功了！它在C:\\temp\\zebra的目录下");
				HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
				DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
				// 获取本机的打印服务
				PrintService[] printService = PrintServiceLookup.lookupPrintServices(flavor, pras);
				for (PrintService printer : printService) {
					if (printer.getName().equals(printName)) {
						DocPrintJob job = printer.createPrintJob();
						try {
							FileInputStream in = new FileInputStream(fileName);
							SimpleDoc doc = new SimpleDoc(in, flavor, null);
							try {
								System.out.println("-------------------------------------开始打印了");
								isExist = true;
								job.print(doc, null);
							} catch (PrintException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}       
				if (!isExist) {
					return "无法获取本地打印机";
				} 
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}

		return null;
	}
	//打印整车装车单
	@Override
	public String printLoadingList(String json) throws IOException {
		// TODO Auto-generated method stub
		Map<?, ?> map = (Map<?, ?>) JSON.parse(json);
		String vin = (String) map.get("vin");
		//String printFunction = (String) map.get("printFunction");
		String printType = (String) map.get("printType");
		String printName = (String) map.get("printName");
		String printUser = (String) map.get("printUser");
		String templateName = (String) map.get("templateName");
		List<Print> list = printDao.isExistPrintLog(vin, printType);
		if(list.size()>0) {
			return "已存在打印记录，请进行重打印！";
		}
		//获取总装配置的流水号信息
		List<PmSerialnumber> serialnumberConfigList = pmSerialnumberDao.getPmSerialnumberConfigInfo("ZZ");
		if(serialnumberConfigList!=null && serialnumberConfigList.size()<1) {
			return "获取总装配置的流水号信息";
		}
		int serialnumber= serialnumberConfigList.get(0).getSerial_number();
		StringBuffer bfBufferProNumber=new StringBuffer(String.valueOf(serialnumber));
		bfBufferProNumber.reverse();
		int size=5-bfBufferProNumber.length();
		for(int i=0;i<size;i++) {
			bfBufferProNumber.append("0");
		}
		bfBufferProNumber.reverse();
		Date d = new Date();
		SimpleDateFormat year = new SimpleDateFormat("yyyy");
		String yearCode= year.format(d).substring(year.format(d).length()-2, year.format(d).length());
		//生成装车单流水号
		String zzSerialnumber="ZZ"+yearCode+bfBufferProNumber;
		ResultBean resultModelColor = getVehicleModelColorByVin(vin);
		if(!resultModelColor.success) {
			/*
			 * result.setSuccess(false); result.setMessage(resultModelColor.message);
			 */
			return resultModelColor.message;
		}
		Map<?, ?> mapModelColor=(Map<?, ?>) resultModelColor.object;
		
		String partNoVersion = (String) mapModelColor.get("STATUSNUM");
		ResultBean resultBean = getPrintParams(vin,printType,partNoVersion);
		if(!resultBean.success) {
			System.out.println(vin+"打印整车装车单"+resultBean.message);
			return "打印整车装车单失败"+resultBean.message;
		}
		
		@SuppressWarnings("unchecked")
		Map<String, Object> parameters = (Map<String, Object>) resultBean.getObject();
		
		parameters.put("printName", printName);

		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
		SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
		String time = df.format(d);
		String date = dt.format(d);

		parameters.put("date",date);
		parameters.put("time", time);
		parameters.put("VIN",vin); 
		parameters.put("serial_number", zzSerialnumber); // 流水号
		parameters.put("vehcile_type", mapModelColor.get("MODEL")); // 车型
		parameters.put("vehcile_color", mapModelColor.get("VEHICLECOLOR"));// 颜色
		 		
		
		System.out.println("-------------------------------------接口通了");
        String filePath = "C://printTemplate//"+templateName+".jasper";
//      String fileName = "LoadingList.jasper";
//		ClassPathResource tempResource = new ClassPathResource("jrxml/LoadingList.jasper");
//		InputStream in =  tempResource.getInputStream();
//      InputStream in = ClassLoader.getSystemResourceAsStream("jrxml/LoadingList.jasper");
        
		JasperPrint jasperPrint;
		Boolean isExist=false;
		System.out.println("-------------------------------------获取模板了");
		try {
			JREmptyDataSource ds = new JREmptyDataSource();
			jasperPrint = JasperFillManager.fillReport(filePath, parameters,ds);
			
	        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
	 
	        DocFlavor flavor = DocFlavor.BYTE_ARRAY.PNG;
	        //获取本机的打印服务
	        PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
	
	        if (printService != null) {
	            for (PrintService p : printService) {
	                if (p.getName().equals(printName)) {
						JRAbstractExporter je = new JRPrintServiceExporter();
						je.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);						
						je.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE,p);
						je.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, false);
						je.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, false);
						
						//打印
						 System.out.println("-------------------------------------开始打印了");
						je.exportReport();
						isExist=true;
	                }
	            }
	        }


		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!isExist) {
			System.out.println("-------------------------------------无法获取本地打印机");
			return "无法获取本地打印机";
		}
		//修改装车单流水号
		PmSerialnumber pmSerialnumber = serialnumberConfigList.get(0);
		pmSerialnumber.setSerial_number(serialnumberConfigList.get(0).getSerial_number()+1);
		pmSerialnumber.setLast_update_time(new Date());
		pmSerialnumber.setLast_update_user(printUser);
		pmSerialnumberDao.updatePmSerialnumber(pmSerialnumber);
		
		//保存打印记录
		Print prBasPrintVinLabel=new Print();
		prBasPrintVinLabel.setVin(vin);
		prBasPrintVinLabel.setPrintType(printType);
		prBasPrintVinLabel.setPrint_status("1");
		prBasPrintVinLabel.setPrintType(printType);
		prBasPrintVinLabel.setTemplateName(templateName);
		prBasPrintVinLabel.setPrintName(printName);
		prBasPrintVinLabel.setPrint_value1((String) mapModelColor.get("MODEL"));
		prBasPrintVinLabel.setPrint_value2((String) mapModelColor.get("VEHICLECOLOR"));
		prBasPrintVinLabel.setPrint_time(new Date());
		prBasPrintVinLabel.setPrint_user(printUser);
		printDao.savePrintInfo(prBasPrintVinLabel);
		//保存装车单流水号
		pmSerialnumber.setVin(vin);
		pmSerialnumber.setZzSerialNum(zzSerialnumber);
		pmSerialnumber.setCreate_user(printUser);
		pmSerialnumber.setCreate_time(new Date());
		pmSerialnumberDao.savePmSerialnumberInfo(pmSerialnumber);
		
		return null;
	}
	//VIn标签打印
	@Override
	public String zebraPrintVinLabel(String json) {
		Boolean isExist = false;
		Map<?, ?> map = (Map<?, ?>) JSON.parse(json);
		// 获取打印参数数据
		String vin = (String) map.get("vin");
		String printType = (String) map.get("printType");
		Boolean printStatus = (Boolean) map.get("printStatus");
		String printName = (String) map.get("printName");
		String printUser = (String) map.get("printUser");
		String templateName =(String) map.get("templateName");
		if (printStatus) {
			List<Print> list = printDao.isExistPrintLog(vin, printType);
			if(list.size()>0) {
				return "已存在打印记录，请进行重打印！";
			}
		} 

		// 保存打印记录
		Print prBasPrintVinLabel = new Print();
		prBasPrintVinLabel.setVin(vin);
		prBasPrintVinLabel.setPrintType(printType);
		prBasPrintVinLabel.setPrint_user(printUser);
		prBasPrintVinLabel.setPrintType(printType);
		prBasPrintVinLabel.setTemplateName(templateName);
		prBasPrintVinLabel.setPrintName(printName);
		if (printStatus) {
			prBasPrintVinLabel.setPrint_status("1");
		} else {
			prBasPrintVinLabel.setPrint_status("2");
		}

		prBasPrintVinLabel.setPrint_time(new Date());
		printDao.savePrintInfo(prBasPrintVinLabel);
		//获取模板
		String filePath = "C://printTemplate//" + templateName + ".zpl";
		try {
			FileReader fileReader = new FileReader(filePath);
			BufferedReader br = new BufferedReader(fileReader);
			String strs = "";
			String datas = null;
			while ((datas = br.readLine()) != null) {
				strs = strs + datas;
			}
			try {
				fileReader.close();
				br.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
			strs = strs.replace("$", vin);
			System.out.println(strs);
			if (strs == null || "".equals(strs)) {
				System.out.println("打印" + vin + "无法获取VIN标签打印模板");
				return "打印" + vin + "无法获取VIN标签打印模板";
			}
			SimpleDateFormat yf = new SimpleDateFormat("yyyyMMddHHmmss");
			Date d = new Date();
			String data = yf.format(d);
			File fileName = new File("C:\\temp\\zebra\\" + vin + "VIN" + data + ".zpl");
			File fileParent = fileName.getParentFile();

			if (!fileParent.exists()) {
				fileParent.mkdirs();
			}

			try {
				fileName.createNewFile();
				FileOutputStream outStream = new FileOutputStream(fileName);
				OutputStreamWriter out = new OutputStreamWriter(outStream, "UTF-8");
//				out.write("^XA");
//				out.write("^MMT");
//				out.write("^PW827");
//				out.write("^LL0236");
//				out.write("^LS0");
//				out.write("^BY4,3,116^FT59,162^BCN,,Y,N");
//				out.write("^FD" + vin + "^FS");
//				out.write("^PQ1,0,1,Y");
//				out.write("^XZ");
				out.write(strs);
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("-------------------------------------生成本地文件成功了！它在C:\\temp\\zebra的目录下");
			HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
			DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
			//获取本机的打印服务
			PrintService[] printService = PrintServiceLookup.lookupPrintServices(flavor, pras);
			for (PrintService printer : printService) {
				if (printer.getName().equals(printName)) {
					DocPrintJob job = printer.createPrintJob();
					try {
						FileInputStream in = new FileInputStream(fileName);
						SimpleDoc doc = new SimpleDoc(in, flavor, null);
						try {
							System.out.println("-------------------------------------开始打印了");
							isExist = true;
							job.print(doc, null);
						} catch (PrintException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}

		if (!isExist) {
			return  "无法获取本地打印机";
		}

		return null;
	}

	//装车单补打
	@Override
	public String printLoadingListAgain(String json) throws ParseException, IOException {
		Map<?, ?> map = (Map<?, ?>) JSON.parse(json);
		String vin = (String) map.get("vin");
		String printType = (String) map.get("printType");
		//String valType = (String) map.get("valType");
		String printName = (String) map.get("printName");
		String printUser = (String) map.get("printUser");
		String templateName = (String) map.get("templateName");
		//获取总装配置的流水号信息
		List<PmSerialnumber> listSerialnumber = pmSerialnumberDao.getPmSerialnumberInfo(vin);
		if(listSerialnumber==null || listSerialnumber.size()<1) {
			return "无法获取总装流水号信息";
		}
		String serialnumber = listSerialnumber.get(0).getZzSerialNum();
		ResultBean resultModelColor = getVehicleModelColorByVin(vin);
		if(!resultModelColor.success) {
			return resultModelColor.message;
		}
		Map<?, ?> mapModelColor=(Map<?, ?>) resultModelColor.object;
		
		//获取装车单配置信息
		String partNoVersion = (String) mapModelColor.get("STATUSNUM");
		ResultBean resultBean = getPrintParams(vin,printType,partNoVersion);
		if(!resultBean.success) {
			System.out.println(vin+"打印整车装车单"+resultBean.message);
			return "打印整车装车单失败"+resultBean.message;
		}
		
		@SuppressWarnings("unchecked")
		Map<String, Object> parameters = (Map<String, Object>) resultBean.getObject();
		
		parameters.put("printName", printName);
		Date d = new Date();
		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
		SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
		String time = df.format(d);
		String date = dt.format(d);

		parameters.put("date",date);
		parameters.put("time", time);
		parameters.put("VIN",vin); 
		parameters.put("serial_number", serialnumber); // 流水号
		parameters.put("vehcile_type", mapModelColor.get("MODEL")); // 车型
		parameters.put("vehcile_color", mapModelColor.get("VEHICLECOLOR"));// 颜色
		 				
		System.out.println("-------------------------------------接口通了");
        String filePath = "C://printTemplate//"+templateName+".jasper";
	//	 ClassPathResource tempResource = new ClassPathResource("jrxml/LoadingList.jasper");
	//   in =  tempResource.getInputStream();

		JasperPrint jasperPrint;
		Boolean isExist=false;
		System.out.println("-------------------------------------获取模板了");
		try {
			JREmptyDataSource ds = new JREmptyDataSource();
			jasperPrint = JasperFillManager.fillReport(filePath, parameters,ds);
			
	        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
	 
	        DocFlavor flavor = DocFlavor.BYTE_ARRAY.PNG;
	        //获取本机的打印服务
	        PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
	
	        if (printService != null) {
	            for (PrintService p : printService) {
	                if (p.getName().equals(printName)) {
						JRAbstractExporter je = new JRPrintServiceExporter();
						je.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);						
			    		je.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE,p);
						je.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, false);
						je.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, false);						
						//打印
					    System.out.println("-------------------------------------开始打印了");
						je.exportReport();
						isExist=true;
	                }
	            }
	        }


		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!isExist) {
			System.out.println("-------------------------------------无法获取本地打印机");
			return "无法获取本地打印机";
		}
		
		//保存打印记录
		Print prBasPrintVinLabel=new Print();
		prBasPrintVinLabel.setVin(vin);
		prBasPrintVinLabel.setPrintType(printType);
		prBasPrintVinLabel.setTemplateName(templateName);
		prBasPrintVinLabel.setPrintName(printName);
		prBasPrintVinLabel.setPrint_status("2");	
		prBasPrintVinLabel.setPrint_value1((String) mapModelColor.get("MODEL"));
		prBasPrintVinLabel.setPrint_value2((String) mapModelColor.get("VEHICLECOLOR"));
		prBasPrintVinLabel.setPrint_time(new Date());
		prBasPrintVinLabel.setPrint_user(printUser);
		printDao.savePrintInfo(prBasPrintVinLabel);
		return null;
	}
	//打印驾驶室装车单
	@Override
	public String printCabList(String json) throws ParseException, IOException {
		// TODO Auto-generated method stub
		Map<?, ?> map = (Map<?, ?>) JSON.parse(json);
		String bsn = (String) map.get("bsn");
	//	String printFunction = (String) map.get("printFunction");
		String printType = (String) map.get("printType");
		String printName = (String) map.get("printName");
		String printUser = (String) map.get("printUser");
		String templateName = (String) map.get("templateName");
		List<Print> list = printDao.isExistPrintLog(bsn, printType);
		if(list.size()>0) {
			return "已存在打印记录，请进行重打印！";
		}
		//获取总装配置的流水号信息
		List<PmSerialnumber> serialnumberConfigList = pmSerialnumberDao.getPmCabSerialnumberConfigInfo("ZZ");
		if(serialnumberConfigList!=null && serialnumberConfigList.size()<1) {
			return "获取总装驾驶室配置的流水号信息";
		}
		int serialnumber= serialnumberConfigList.get(0).getSerial_number();
		StringBuffer bfBufferProNumber=new StringBuffer(String.valueOf(serialnumber));
		bfBufferProNumber.reverse();
		int size=5-bfBufferProNumber.length();
		for(int i=0;i<size;i++) {
			bfBufferProNumber.append("0");
		}
		bfBufferProNumber.reverse();
		Date d = new Date();
		SimpleDateFormat year = new SimpleDateFormat("yyyy");
		String yearCode= year.format(d).substring(year.format(d).length()-2, year.format(d).length());
		//生成装车单流水号
		String zzSerialnumber="ZZ"+yearCode+bfBufferProNumber;
		ResultBean resultModelColor = getVehicleModelColorByVin(bsn);
		if(!resultModelColor.success) {
			return resultModelColor.message;
		}
		Map<?, ?> mapModelColor=(Map<?, ?>) resultModelColor.object;
		
		//获取装车单配置信息
		String partNoVersion = (String) mapModelColor.get("STATUSNUM");
		ResultBean resultBean = getPrintParams(bsn,printType,partNoVersion);
		if(!resultBean.success) {
			System.out.println(bsn+"打印整车装车单"+resultBean.message);
			return "打印整车装车单失败"+resultBean.message;
		}
		
		@SuppressWarnings("unchecked")
		Map<String, Object> parameters = (Map<String, Object>) resultBean.getObject();
		
		parameters.put("printName", printName);

		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
		SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
		String time = df.format(d);
		String date = dt.format(d);

		parameters.put("date",date);
		parameters.put("time", time);
		parameters.put("VIN",bsn); 
		parameters.put("serial_number", zzSerialnumber); // 流水号
		parameters.put("vehcile_type", mapModelColor.get("MODEL")); // 车型
		parameters.put("vehcile_color", mapModelColor.get("VEHICLECOLOR"));// 颜色
		 				
		System.out.println("-------------------------------------接口通了");
        String filePath = "C://printTemplate//"+templateName+".jasper";
//      String fileName = "LoadingList.jasper";
//	    ClassPathResource tempResource = new ClassPathResource("jrxml/cabList.jasper");
//      InputStream in =  tempResource.getInputStream();
//      InputStream in = ClassLoader.getSystemResourceAsStream("jrxml/LoadingList.jasper");
		JasperPrint jasperPrint;
		Boolean isExist=false;
		System.out.println("-------------------------------------获取模板了");
		try {
			JREmptyDataSource ds = new JREmptyDataSource();
			jasperPrint = JasperFillManager.fillReport(filePath, parameters,ds);
			
	        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
	 
	        DocFlavor flavor = DocFlavor.BYTE_ARRAY.PNG;
	        //���õĴ�ӡ���б�(�ַ�������)
	        PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
	
	        if (printService != null) {
	            for (PrintService p : printService) {
	                if (p.getName().equals(printName)) {
						JRAbstractExporter je = new JRPrintServiceExporter();
						je.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
						je.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE,p);
						je.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, false);
						je.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, false);						
						//打印
						 System.out.println("-------------------------------------开始打印了");
						je.exportReport();
						isExist=true;
	                }
	            }
	        }


		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!isExist) {
			System.out.println("-------------------------------------无法获取本地打印机");
			return "无法获取本地打印机";
		}
		//修改装车单流水号
		PmSerialnumber pmSerialnumber = serialnumberConfigList.get(0);
		pmSerialnumber.setSerial_number(serialnumberConfigList.get(0).getSerial_number()+1);
		pmSerialnumber.setLast_update_time(new Date());
		pmSerialnumber.setLast_update_user(printUser);
		pmSerialnumberDao.updatePmCabSerialnumber(pmSerialnumber);
		
		//保存打印记录
		Print prBasPrintVinLabel=new Print();
		prBasPrintVinLabel.setVin(bsn);
		prBasPrintVinLabel.setPrintType(printType);
		prBasPrintVinLabel.setTemplateName(templateName);
		prBasPrintVinLabel.setPrintName(printName);
		prBasPrintVinLabel.setPrint_status("1");	
		prBasPrintVinLabel.setPrint_value1((String) mapModelColor.get("MODEL"));
		prBasPrintVinLabel.setPrint_value2((String) mapModelColor.get("VEHICLECOLOR"));
		prBasPrintVinLabel.setPrint_time(new Date());
		prBasPrintVinLabel.setPrint_user(printUser);
		printDao.savePrintInfo(prBasPrintVinLabel);
		//保存装车单流水号
		pmSerialnumber.setVin(bsn);
		pmSerialnumber.setZzSerialNum(zzSerialnumber);
		pmSerialnumber.setCreate_user(printUser);
		pmSerialnumber.setCreate_time(new Date());
		pmSerialnumberDao.savePmSerialnumberInfo(pmSerialnumber);
		
		return null;

	}
	@Override
	public String printCabListAgain(String json) throws ParseException, IOException {
		Map<?, ?> map = (Map<?, ?>) JSON.parse(json);
		String bsn = (String) map.get("bsn");
		//String printFunction = (String) map.get("printFunction");
		String printType = (String) map.get("printType");
		String printName = (String) map.get("printName");
		String printUser = (String) map.get("printUser");
		String templateName = (String) map.get("templateName");
		//获取总装配置的流水号信息
		List<PmSerialnumber> listSerialnumber = pmSerialnumberDao.getPmSerialnumberInfo(bsn);
		if(listSerialnumber==null || listSerialnumber.size()<1) {
			return "无法获取总装流水号信息";
		}
		String serialnumber = listSerialnumber.get(0).getZzSerialNum();
		ResultBean resultModelColor = getVehicleModelColorByVin(bsn);
		if(!resultModelColor.success) {
			return resultModelColor.message;
		}
		Map<?, ?> mapModelColor=(Map<?, ?>) resultModelColor.object;
		
		//获取装车单配置信息
		String partNoVersion = (String) mapModelColor.get("STATUSNUM");
		ResultBean resultBean = getPrintParams(bsn,printType,partNoVersion);
		if(!resultBean.success) {
			System.out.println(bsn+"打印整车装车单"+resultBean.message);
			return "打印整车装车单失败"+resultBean.message;
		}
		
		@SuppressWarnings("unchecked")
		Map<String, Object> parameters = (Map<String, Object>) resultBean.getObject();
		
		parameters.put("printName", printName);
		Date d = new Date();
		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
		SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
		String time = df.format(d);
		String date = dt.format(d);

		parameters.put("date",date);
		parameters.put("time", time);
		parameters.put("VIN",bsn); 
		parameters.put("serial_number", serialnumber); // 流水号
		parameters.put("vehcile_type", mapModelColor.get("MODEL")); // 车型
		parameters.put("vehcile_color", mapModelColor.get("VEHICLECOLOR"));// 颜色
		 				
		System.out.println("-------------------------------------接口通了");
        String filePath = "C://printTemplate//"+templateName+".jasper";
		// ClassPathResource tempResource = new ClassPathResource("jrxml/cabList.jasper");
		// InputStream in =  tempResource.getInputStream();
		JasperPrint jasperPrint;
		Boolean isExist=false;
		System.out.println("-------------------------------------获取模板了");
		try {
			JREmptyDataSource ds = new JREmptyDataSource();
			jasperPrint = JasperFillManager.fillReport(filePath, parameters,ds);
			
	        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
	 
	        DocFlavor flavor = DocFlavor.BYTE_ARRAY.PNG;
	        //获取本机的打印服务
	        PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
	
	        if (printService != null) {
	            for (PrintService p : printService) {
	                if (p.getName().equals(printName)) {
						JRAbstractExporter je = new JRPrintServiceExporter();
						je.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);						
						je.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE,p);
						je.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, false);
						je.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, false);
						
						//打印
						 System.out.println("-------------------------------------开始打印了");
						je.exportReport();
						isExist=true;
	                }
	            }
	        }


		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!isExist) {
			System.out.println("-------------------------------------无法获取本地打印机");
			return "无法获取本地打印机";
		}
		
		//保存打印记录
		Print prBasPrintVinLabel=new Print();
		prBasPrintVinLabel.setVin(bsn);
		prBasPrintVinLabel.setPrintType(printType);
		prBasPrintVinLabel.setTemplateName(templateName);
		prBasPrintVinLabel.setPrintName(printName);
		prBasPrintVinLabel.setPrint_status("2");	
		prBasPrintVinLabel.setPrint_value1((String) mapModelColor.get("MODEL"));
		prBasPrintVinLabel.setPrint_value2((String) mapModelColor.get("VEHICLECOLOR"));
		prBasPrintVinLabel.setPrint_time(new Date());
		prBasPrintVinLabel.setPrint_user(printUser);
		printDao.savePrintInfo(prBasPrintVinLabel);
		return null;
	}



//通过vin获取车型和颜色
	public ResultBean getVehicleModelColorByVin(String vin) {
		// TODO Auto-generated method stub
		ResultBean result  = new ResultBean(true,"'");
		result.setSuccess(true);
		
		List<TwBasLot> lotList = lotDao.selectTwBasLotByVinOrSelf(vin);
		if(lotList==null ||lotList.size()<1) {
			result.setSuccess(false);
			result.setMessage("无法获取车辆信息");
			return result;
		}
		TwBasLot basLot = lotList.get(0);
		String partNoVersion=basLot.getPartNoVersion();
		
		if(partNoVersion==null ||  "".equals(partNoVersion)) {
			result.setSuccess(false);
			result.setMessage("无法获取物料号信息");
			return result;
		}
		String paintColorNum =partNoVersion.substring(partNoVersion.length()-9, partNoVersion.length()-8);
		String colorNum =partNoVersion.substring(partNoVersion.length()-8, partNoVersion.length()-6);
		String model="";
		String paintColor="";
		String color="";
		Map<String,Object> parameters = new HashMap<String,Object>(); 
		//获取车型
		List<PmPartModelAndVinRule> listVinRuleInfo = vinRuleDao.getVinRuleInfo(partNoVersion);
		if(listVinRuleInfo==null || listVinRuleInfo.size()<1 ) {
			result.setSuccess(false);
			result.setMessage("无法获取车型配置信息");
			return result;
		}
		model = listVinRuleInfo.get(0).getModel();
		//获取车漆配置信息
		List<PmFeaturValue> paintColorNumList  = pmFeaturValueDao.getFeaturValueByType("vehiclePaintType",paintColorNum);
		if(paintColorNumList.size()<1) {
			result.setSuccess(false);
			result.setMessage("无法获取车漆属性配置信息");
			return result;
		}
		paintColor=paintColorNumList.get(0).getFeatue_value_desc();
		//获取颜色配置信息
		List<PmFeaturValue> colorNumList  = pmFeaturValueDao.getFeaturValueByType("vehicleColor",colorNum);
		if(colorNumList.size()<1) {
			result.setSuccess(false);
			result.setMessage("无法获取车漆颜色配置信息");
			return result;
		}
		color=colorNumList.get(0).getFeatue_value_desc();
		parameters.put("MODEL",model);
		parameters.put("VEHICLECOLOR", paintColor+color);
		parameters.put("STATUSNUM", partNoVersion);
		result.setObject(parameters);
		
		
		
		return result;
	}

	//获取打印参数
	public ResultBean getPrintParams(String vinOrSelf,String configType,String partNoVersion){
		
		ResultBean result = new ResultBean(true, "'");
		result.setSuccess(true);
		//通过vin或者自编号获取特殊要求
		Map<String, Object> parameters = new HashMap<String, Object>();
		List<TwBasLot> getspecialRequireList = lotDao.getspecialRequire(vinOrSelf);
		if(getspecialRequireList!=null && getspecialRequireList.size()>0) {
			if(getspecialRequireList.get(0)!=null &&!"".equals(getspecialRequireList.get(0))) {
				parameters.put("parameter171", getspecialRequireList.get(0).getSpecialRequire());
			}					
		}
		//通过成品物料号和配置类型获取装车单配置内容
		List<PrBasLoadingList> listLoading = listDao.getLoadingListByConfigType(configType, partNoVersion);
		if (listLoading == null || listLoading.size() < 1) {
			result.setSuccess(false);
			result.setMessage("无法获取装车单配置信息");
			return result;
		}
		parameters.put("header", listLoading.get(0).getHeadInfo());
		for(int i=0;i<listLoading.size();i++) {
			switch (listLoading.get(i).getSerialNum()) {
			case "1":
				parameters.put("parameter11", listLoading.get(i).getPartDesc());
				parameters.put("parameter21", listLoading.get(i).getPartNo());
				break;
			case "2":
				parameters.put("parameter12", listLoading.get(i).getPartDesc());
				parameters.put("parameter22", listLoading.get(i).getPartNo());
				break;
			case "3":
				parameters.put("parameter13", listLoading.get(i).getPartDesc());
				parameters.put("parameter23", listLoading.get(i).getPartNo());
				break;
			case "4":
				parameters.put("parameter14", listLoading.get(i).getPartDesc());
				parameters.put("parameter24", listLoading.get(i).getPartNo());
				break;
			case "5":
				parameters.put("parameter31", listLoading.get(i).getPartDesc());
				parameters.put("parameter41", listLoading.get(i).getPartNo());
				break;
			case "6":
				parameters.put("parameter32", listLoading.get(i).getPartDesc());
				parameters.put("parameter42", listLoading.get(i).getPartNo());
				break;
			case "7":
				parameters.put("parameter33", listLoading.get(i).getPartDesc());
				parameters.put("parameter43", listLoading.get(i).getPartNo());
				break;
			case "8":
				parameters.put("parameter34", listLoading.get(i).getPartDesc());
				parameters.put("parameter44", listLoading.get(i).getPartNo());
				break;
			case "9":
				parameters.put("parameter51", listLoading.get(i).getPartDesc());
				parameters.put("parameter61", listLoading.get(i).getPartNo());
				break;
			case "10":
				parameters.put("parameter52", listLoading.get(i).getPartDesc());
				parameters.put("parameter62", listLoading.get(i).getPartNo());
				break;
			case "11":
				parameters.put("parameter53", listLoading.get(i).getPartDesc());
				parameters.put("parameter63", listLoading.get(i).getPartNo());
				break;
			case "12":
				parameters.put("parameter54", listLoading.get(i).getPartDesc());
				parameters.put("parameter64", listLoading.get(i).getPartNo());
				break;
			case "13":
				parameters.put("parameter71", listLoading.get(i).getPartDesc());
				parameters.put("parameter82", listLoading.get(i).getPartNo());
				break;
			case "14":
				parameters.put("parameter72", listLoading.get(i).getPartDesc());
				parameters.put("parameter82", listLoading.get(i).getPartNo());
				break;
			case "15":
				parameters.put("parameter73", listLoading.get(i).getPartDesc());
				parameters.put("parameter83", listLoading.get(i).getPartNo());
				break;
			case "16":
				parameters.put("parameter74", listLoading.get(i).getPartDesc());
				parameters.put("parameter84", listLoading.get(i).getPartNo());
				break;
			case "17":
				parameters.put("parameter91", listLoading.get(i).getPartDesc());
				parameters.put("parameter101", listLoading.get(i).getPartNo());
				break;
			case "18":
				parameters.put("parameter92", listLoading.get(i).getPartDesc());
				parameters.put("parameter102", listLoading.get(i).getPartNo());
				break;
			case "19":
				parameters.put("parameter93", listLoading.get(i).getPartDesc());
				parameters.put("parameter103", listLoading.get(i).getPartNo());
				break;
			case "20":
				parameters.put("parameter94", listLoading.get(i).getPartDesc());
				parameters.put("parameter104", listLoading.get(i).getPartNo());
				break;
			case "21":
				parameters.put("parameter111", listLoading.get(i).getPartDesc());
				parameters.put("parameter121", listLoading.get(i).getPartNo());
				break;
			case "22":
				parameters.put("parameter112", listLoading.get(i).getPartDesc());
				parameters.put("parameter122", listLoading.get(i).getPartNo());
				break;
			case "23":
				parameters.put("parameter113", listLoading.get(i).getPartDesc());
				parameters.put("parameter123", listLoading.get(i).getPartNo());
				break;
			case "24":
				parameters.put("parameter114", listLoading.get(i).getPartDesc());
				parameters.put("parameter124", listLoading.get(i).getPartNo());
				break;
			case "25":
				parameters.put("parameter131", listLoading.get(i).getPartDesc());
				parameters.put("parameter141", listLoading.get(i).getPartNo());
				break;
			case "26":
				parameters.put("parameter132", listLoading.get(i).getPartDesc());
				parameters.put("parameter142", listLoading.get(i).getPartNo());
				break;
			case "27":
				parameters.put("parameter133", listLoading.get(i).getPartDesc());
				parameters.put("parameter143", listLoading.get(i).getPartNo());
				break;
			case "28":
				parameters.put("parameter134", listLoading.get(i).getPartDesc());
				parameters.put("parameter144", listLoading.get(i).getPartNo());
				break;
			case "29":
				parameters.put("parameter151", listLoading.get(i).getPartDesc());
				parameters.put("parameter161", listLoading.get(i).getPartNo());
				break;
			case "30":
				parameters.put("parameter152", listLoading.get(i).getPartDesc());
				parameters.put("parameter162", listLoading.get(i).getPartNo());
				break;
			case "31":
				parameters.put("parameter153", listLoading.get(i).getPartDesc());
				parameters.put("parameter163", listLoading.get(i).getPartNo());
				break;
			case "32":
				parameters.put("parameter154", listLoading.get(i).getPartDesc());
				parameters.put("parameter164", listLoading.get(i).getPartNo());
				break;
			default:
				break;
			}
		}
		result.setObject(parameters);
		return result;
		
	}

	
	

}
